package com.cqs.leetcode.tree;

import com.cqs.leetcode.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class BinaryTreePreorderTraversal144 {

    class Solution {
        public List<Integer> preorderTraversal(TreeNode root) {
            List<Integer> list = new ArrayList<>();
            preorderTraversal(root, list);
            return list;
        }

        private void preorderTraversal(TreeNode root, List<Integer> list) {
            if (root == null) return;
            //遍历根节点
            list.add(root.val);
            //遍历左子树
            preorderTraversal(root.left, list);
            //遍历右子树
            preorderTraversal(root.right, list);
        }
    }

    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (stack.size() > 0) {
            TreeNode pop = stack.pop();
            list.add(pop.val);
            //右子树后访问，先入栈
            if (pop.right != null) stack.push(pop.right);
            //左子树入栈
            if (pop.left != null) stack.push(pop.left);

        }
        return list;
    }
}
